<template>
  <div class="app-container" ref="appContainer">
    <PropTable
      ref="tableData"
      :loading="loading"
      :columns="column"
      :data="data"
      @reset="reset"
      @onSubmit="onSubmit"
      @add="add"
      @change="changeUserState"
    >
      <template v-slot:operation="scope">
        <el-button type="primary" size="small" icon="Edit" @click="edit(scope.row)">
          编辑
        </el-button>
        <!--  <el-button @click="del(scope.row)" type="danger" size="small" icon="Delete">
          删除
        </el-button>-->
      </template>
    </PropTable>

    <el-drawer v-model="dialogVisible" title="编辑">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
      >
        <el-form-item label="姓名：" prop="nickname">
          <el-input v-model="ruleForm.nickname" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="部门：" prop="department">
          <el-select
            v-model="ruleForm.department"
            placeholder="请选择部门"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="ite in depList"
              :key="ite.value"
              :label="ite.label"
              :value="ite.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="职务：" prop="title">
          <el-select
            v-model="ruleForm.title"
            placeholder="请选择职务"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="ite in titleList"
              :key="ite.value"
              :label="ite.label"
              :value="ite.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色：" prop="position">
          <el-select
            v-model="ruleForm.position"
            placeholder="请选择角色"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="ite in posList"
              :key="ite.value"
              :label="ite.label"
              :value="ite.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input v-model="ruleForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleClose(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-drawer>
    <el-drawer v-model="dialogVisible2" title="新增">
      <el-form
        ref="ruleFormRef2"
        :model="newUser"
        :rules="rules2"
        label-width="120px"
        class="demo-ruleForm2"
        :size="formSize"
      >
        <el-form-item label="姓名：" prop="nickname">
          <el-input v-model="newUser.nickname" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="部门：" prop="department">
          <el-select
            v-model="newUser.department"
            placeholder="请选择部门"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="ite in depList"
              :key="ite.value"
              :label="ite.label"
              :value="ite.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="职务：" prop="title">
          <el-select
            v-model="newUser.title"
            placeholder="请选择职务"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="ite in titleList"
              :key="ite.value"
              :label="ite.label"
              :value="ite.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色：" prop="position">
          <el-select v-model="newUser.position" placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="ite in posList"
              :key="ite.value"
              :label="ite.label"
              :value="ite.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="电话：" prop="phone">
          <el-input v-model="newUser.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input v-model="newUser.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取消</el-button>
          <el-button type="primary" @click="addUser(ruleFormRef2)">确定</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>
<script lang="ts" setup name="comprehensive">
  import { ref, reactive, onMounted, nextTick } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import {
    postSysUserSearch,
    deleteSysUserDel,
    putSysUserEnabled,
    getSysDepList,
    getSysPosList,
    postSysUserEdit,
  } from '@/api/controller/sys-user-controller/index'
  import { postAuthRegister } from '@/api/controller/login-controller/index'
  import { getSysSysRoleList } from '@/api/controller/sys-user-controller/index'
  const loading = ref(true)
  const appContainer = ref(null)
  import PropTable from '@/components/Table/PropTable/index.vue'

  const column = [
    { name: 'nickname', label: '姓名', inSearch: true, valueType: 'input' },
    { name: 'department', label: '部门', inSearch: true, valueType: 'input' },
    { name: 'title', label: '职务', inSearch: true, valueType: 'input' },
    { name: 'position', label: '角色', valueType: 'input', showType: 'tag', itemIf: true },
    { name: 'enabled', label: '用户状态', itemIf: true, width: 140 },
    { name: 'phone', label: '电话', inSearch: true, valueType: 'input', width: 140 },
    { name: 'email', label: '邮箱', valueType: 'input' },
    { name: 'operation', slot: true, fixed: 'right', width: 120, label: '操作' },
  ]
  const data = ref(null)

  const formSize = ref('default')
  const ruleFormRef = ref<FormInstance>()
  const ruleFormRef2 = ref<FormInstance>()
  const ruleForm = ref({
    nickname: null,
    department: null,
    title: null,
    position: null,
    phone: null,
    email: null,
  })

  const rules = reactive({
    nickname: [
      { required: true, message: '请输入姓名', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    department: [
      { required: true, message: '请输入部门', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    title: [
      { required: true, message: '请输入职务', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    position: [
      { required: true, message: '请选择角色', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    email: [
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
  })

  const rules2 = reactive({
    nickname: [
      { required: true, message: '请输入姓名', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    department: [
      { required: true, message: '请输入部门', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    title: [
      { required: true, message: '请输入职务', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    position: [{ required: true, message: '请选择角色', trigger: 'blur' }],
    phone: [
      { required: true, message: '请输入电话', trigger: 'blur' },
      {
        pattern: /^(1[3456789]\d{9}|0\d{2,3}-\d{7,8})$/,
        message: '请输入正确的电话格式',
        trigger: 'blur',
      },
    ],
    email: [
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
  })
  const dialogVisible = ref(false)
  const dialogVisible2 = ref(false)
  const tableData = ref(null)
  //修改
  const handleClose = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        const result = await postSysUserEdit(ruleForm.value, { loading: true })
        if (result.code === 200) {
          try {
            loading.value = true
            const result = await postSysUserSearch(tableData.value?.formInline)
            data.value = result.data
            dialogVisible.value = false
            ElMessage.success('修改成功')
          } finally {
            loading.value = false
          }
        }
      } else {
        ElMessage.warning('请正确填写表单')
        return false
      }
    })
  }
  // 打开新增弹窗
  const newUser = ref({
    nickname: null,
    department: null,
    title: null,
    position: null,
    phone: null,
    email: null,
  })
  const add = () => {
    for (let key in newUser.value) {
      newUser.value[key] = null
    }
    dialogVisible2.value = true
    nextTick(() => {
      ruleFormRef2.value.clearValidate()
    })
  }

  //新增一个用户
  const addUser = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        const result = await postAuthRegister(newUser.value, { loading: true })
        if (result.code === 200) {
          try {
            loading.value = true
            const result = await postSysUserSearch(tableData.value?.formInline)
            data.value = result.data
            dialogVisible2.value = false
            ElMessage.success('添加成功')
          } finally {
            loading.value = false
          }
        }
      } else {
        ElMessage.warning('请正确填写表单')
        return false
      }
    })
  }

  //打开编辑弹窗
  const edit = (row) => {
    ruleForm.value = { ...row }
    dialogVisible.value = true
    nextTick(() => {
      ruleFormRef.value.clearValidate()
    })
  }
  // 删除当前项
  const del = async (row) => {
    ElMessageBox.confirm('你确定要删除当前项吗?', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    })
      .then(async () => {
        const result = await deleteSysUserDel({ id: row.id })
        if (result.code === 200) {
          loading.value = true
          const result = await postSysUserSearch(tableData.value?.formInline)
          data.value = result.data
          dialogVisible.value = false
          loading.value = false
          ElMessage.success('删除成功')
        }
      })
      .catch(() => {
        console.log('错误')
      })
  }
  //重置搜索条件
  const reset = async () => {
    try {
      loading.value = true
      let pageInfo = {
        pageNum: 1,
        pageSize: 15,
      }
      const result = await postSysUserSearch(pageInfo)
      data.value = result.data
    } finally {
      loading.value = false
    }
  }
  //搜索
  const onSubmit = async (val) => {
    try {
      loading.value = true
      const result = await postSysUserSearch(val)
      data.value = result.data
    } finally {
      loading.value = false
    }
  }
  const depList = ref([])
  const titleList = ref([])
  const posList = ref([])
  //初始化
  onMounted(async () => {
    try {
      loading.value = true
      getSysDepList().then((res) => {
        depList.value = res.data
      })
      getSysPosList().then((res) => {
        titleList.value = res.data
      })
      getSysSysRoleList().then((res) => {
        posList.value = res.data
      })
      let pageInfo = {
        pageNum: 1,
        pageSize: 15,
      }
      const result = await postSysUserSearch(pageInfo)
      data.value = result.data
    } finally {
      loading.value = false
    }
  })
  //改变用户状态
  const changeUserState = async (id, enabled, str) => {
    const data = {
      id: id,
      enabled: enabled,
    }
    const res = await putSysUserEnabled(data, { loading: true })
    ElMessage.success(res.data)
  }
</script>

<style scoped>
  .edit-input {
    padding-right: 100px;
  }
  .app-container {
    flex: 1;
    display: flex;
    width: 100%;
    padding: 16px;
    box-sizing: border-box;
  }
  .cancel-btn {
    position: absolute;
    right: 15px;
    top: 10px;
  }
</style>
